<template>
  <view class="review-container">
    <Loading :show="isLoading" />
    <view v-if="!isLoading">
      <view v-if="orderDetail" class="order-card">
        <view class="order-header">
          <text class="order-title">订单号：{{ orderDetail.orderNo }}</text>
          <text class="order-amount">实付金额：¥{{ orderDetail.actualAmount }}</text>
        </view>
        <view class="order-products">
          <view v-for="item in orderDetail.orderDetail" :key="item.id" class="product-item">
            <image class="product-image" :src="item.productImage" mode="aspectFill" />
            <view class="product-info">
              <text class="product-name">{{ item.productName }}</text>
              <text class="product-price">¥{{ item.price }}</text>
              <text class="product-quantity">x{{ item.quantity }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 评论状态提示，仅已评论时显示 -->
      <view v-if="hasReviewed" class="review-status-bar">
        <text>评论状态：{{ getStatusText(reviewInfo.status) }}</text>
      </view>

      <view v-if="hasReviewed" class="reviewed-tip">
        <text>该订单已评价</text>
        <view class="reviewed-content">
          <text>评分：{{ reviewInfo.rating }} 分</text>
          <text>内容：{{ reviewInfo.content }}</text>
          <view v-if="reviewInfo.images">
            <image v-for="(img, idx) in reviewInfo.images.split(',')" :key="idx" class="review-image" :src="img" mode="aspectFill" />
          </view>
        </view>
      </view>

      <view v-else>
        <view v-if="!submitSuccess" class="review-form-card">
          <view class="form-row star-row">
            <text class="form-label">评分：</text>
            <view class="star-group">
              <view v-for="n in 5" :key="n" class="star-wrap">
                <text class="star half" :class="rating >= n - 0.5 ? 'active' : ''" @tap="setRatingHalf(n)">&#9733;</text>
                <text class="star full" :class="rating >= n ? 'active' : ''" @tap="setRatingFull(n)">&#9733;</text>
              </view>
              <input class="rating-input" v-model.number="ratingInput" @input="onRatingInput" type="number" min="0.5" max="5" step="0.1" />
            </view>
            <text class="rating-value">{{ rating }} 分</text>
          </view>
          <view class="form-row">
            <text class="form-label">评论内容：</text>
            <textarea class="review-textarea" v-model="content" placeholder="请输入您的评价"></textarea>
          </view>
          <view class="form-row">
            <text class="form-label">上传图片：</text>
            <view class="image-list">
              <view v-for="(img, idx) in images" :key="idx" class="review-image-item">
                <image class="review-image" :src="img" mode="aspectFill" />
                <text class="delete-btn" @tap="deleteImageTap(idx)">×</text>
              </view>
              <view v-if="images.length < 6" class="upload-btn" @tap="chooseImage">
                <text class="upload-icon">+</text>
              </view>
            </view>
          </view>
          <button class="submit-btn" :disabled="isLoading" @tap="submitReview">提交评论</button>
        </view>
        <view v-else class="success-tip">
          <text>评论已提交，待审核！</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { addReview, getOrderReviewByOrder } from '@/api/order/orderReview';
import { getByOrderNo } from '@/api/order';
import { uploadAvatar } from '@/api/oss';
import Loading from '@/components/Loading.vue';

const orderNo = ref('');
const orderDetail = ref<any>(null);
const rating = ref(5);
const content = ref('');
const images = ref<string[]>([]);
const isLoading = ref(true);
const submitSuccess = ref(false);
const ratingInput = ref(5);
const hoverRating = ref(0);
const hasReviewed = ref(false);
const reviewInfo = ref<any>(null);

const setRating = (val: number) => {
  rating.value = val;
  ratingInput.value = val;
};

const onRatingInput = (e: any) => {
  let val = parseFloat(e.detail.value || e.target.value || ratingInput.value);
  if (isNaN(val)) val = 5;
  if (val < 0.5) val = 0.5;
  if (val > 5) val = 5;
  // 保留一位小数
  val = Math.round(val * 10) / 10;
  rating.value = val;
  ratingInput.value = val;
};

// 获取订单详情
const fetchOrderDetail = async (orderNoVal: string) => {
  try {
    isLoading.value = true;
    const res = await getByOrderNo(orderNoVal);
    if (res.code === 200) {
      orderDetail.value = res.data;
      
      // 查询是否已评价
      await checkOrderReviewed(res.data.id);
    }
  } catch (e) {
    uni.showToast({ title: '获取订单信息失败', icon: 'none' });
  } finally {
    isLoading.value = false;
  }
};

const checkOrderReviewed = async (orderId: number) => {
  try {
    const res = await getOrderReviewByOrder(orderId);
    console.log(res);
    if (res.code === 200 && res.data) {
      hasReviewed.value = true;
      reviewInfo.value = res.data;
    } else {
      hasReviewed.value = false;
    }
  } catch (e) {
    hasReviewed.value = false;
  }
};

// 选择图片（本地路径，页面立即显示）
const chooseImage = () => {
  if (images.value.length >= 6) return;
  uni.chooseImage({
    count: 6 - images.value.length,
    success: (res) => {
      images.value = [...images.value, ...res.tempFilePaths];
    }
  });
};

// 删除图片
const deleteImage = (idx: number) => {
  images.value.splice(idx, 1);
};

// 替换星星点击事件，避免匿名函数导致类型推断问题
const setRatingHalf = (n: number) => setRating(n - 0.5);
const setRatingFull = (n: number) => setRating(n);
// 替换图片删除事件
const deleteImageTap = (idx: number) => deleteImage(idx);

// 提交评论时上传图片，收集 ossId
const submitReview = async () => {
  if (!content.value.trim()) {
    uni.showToast({ title: '请输入评论内容', icon: 'none' });
    return;
  }
  isLoading.value = true;
  try {
    uni.showLoading({ title: '提交中...' });
    // 上传图片，收集 ossId
    let ossIds: string[] = [];
    for (const filePath of images.value) {
      const res = await uploadAvatar(filePath);
      if (res.code === 200 && res.data && res.data.ossId) {
        ossIds.push(res.data.ossId);
      }
    }
    const userInfo = uni.getStorageSync('userInfo');
    const reviewData = {
      id: null,
      orderId: orderDetail.value.id,
      orderNo: orderDetail.value.orderNo,
      userId: userInfo.id,
      rating: Math.round(rating.value * 2) / 2,
      content: content.value,
      images: ossIds.join(','),
      status: 0,
      createTime: null,
      updateTime: null
    };
    const res = await addReview(reviewData);
    if (res.code === 200) {
      submitSuccess.value = true;
    } else {
      uni.showToast({ title: res.msg || '提交失败', icon: 'none' });
    }
  } catch (e) {
    uni.showToast({ title: '提交失败', icon: 'none' });
  } finally {
    isLoading.value = false;
    uni.hideLoading();
  }
};

const getStatusText = (status: number) => {
  if (status === 0) return '待审核';
  if (status === 1) return '已发布';
  if (status === 2) return '已拒绝';
  return '';
};

onLoad((options: any) => {
  if (options?.orderNo) {
    orderNo.value = options.orderNo;
    fetchOrderDetail(options.orderNo);
  }
});
</script>

<style>
.review-container {
  padding: 32rpx 0 32rpx 0;
  background: #f7f8fa;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.order-card {
  width: 92vw;
  background: #fff;
  border-radius: 22rpx;
  box-shadow: 0 8rpx 32rpx rgba(255,107,107,0.08), 0 2rpx 8rpx #ffd70011;
  padding: 40rpx 32rpx 24rpx 32rpx;
  margin-bottom: 36rpx;
}
.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 18rpx;
}
.order-title {
  font-size: 30rpx;
  color: #333;
  font-weight: 600;
}
.order-amount {
  font-size: 28rpx;
  color: #ff4d4f;
  font-weight: 500;
}
.order-products {
  margin-top: 10rpx;
}
.product-item {
  display: flex;
  align-items: center;
  margin-bottom: 10rpx;
}
.product-image {
  width: 80rpx;
  height: 80rpx;
  border-radius: 10rpx;
  margin-right: 18rpx;
}
.product-info {
  flex: 1;
}
.product-name {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}
.product-price {
  font-size: 26rpx;
  color: #ff6b6b;
  margin-right: 10rpx;
}
.product-quantity {
  font-size: 24rpx;
  color: #999;
}
.review-form-card {
  width: 92vw;
  background: #fff;
  border-radius: 22rpx;
  box-shadow: 0 8rpx 32rpx rgba(255,107,107,0.08), 0 2rpx 8rpx #ffd70011;
  padding: 40rpx 32rpx 24rpx 32rpx;
  margin-bottom: 36rpx;
}
.form-row {
  display: flex;
  align-items: flex-start;
  margin-bottom: 28rpx;
}
.form-label {
  width: 110rpx;
  color: #333;
  font-size: 28rpx;
  margin-top: 8rpx;
  font-weight: 500;
}
.star-row {
  align-items: center;
  justify-content: flex-start;
  margin-bottom: 36rpx;
}
.star-group {
  display: flex;
  align-items: center;
  gap: 2rpx;
  position: relative;
  margin-right: 18rpx;
}
.star-wrap {
  position: relative;
  width: 44rpx;
  height: 44rpx;
  line-height: 44rpx;
  display: inline-block;
}
.star {
  font-size: 44rpx;
  color: #e0e0e0;
  position: absolute;
  left: 0;
  top: 0;
  width: 50%;
  height: 100%;
  overflow: hidden;
  transition: color 0.2s, transform 0.18s, text-shadow 0.18s;
  cursor: pointer;
  z-index: 1;
  text-shadow: 0 2rpx 8rpx #ffd70022;
}
.star.full {
  left: 0;
  width: 100%;
  color: #e0e0e0;
  z-index: 2;
}
.star.full.active,
.star.half.active {
  color: #ffb300;
  background: linear-gradient(90deg, #ffb300 60%, #ff6b6b 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  text-shadow: 0 4rpx 16rpx #ffd70099, 0 2rpx 8rpx #ffb30044;
  transform: scale(1.18) rotate(-3deg);
  filter: drop-shadow(0 0 8rpx #ffb30088);
}
.star:hover {
  color: #ffd700;
  transform: scale(1.22) rotate(2deg);
  text-shadow: 0 6rpx 18rpx #ffd700cc;
}
.rating-input {
  width: 80rpx;
  height: 44rpx;
  margin-left: 18rpx;
  border: 1px solid #ffd700;
  border-radius: 12rpx;
  font-size: 30rpx;
  color: #ffb300;
  text-align: center;
  background: #fffbe6;
  outline: none;
  box-shadow: 0 2rpx 8rpx #ffd70022;
  font-weight: 600;
}
.rating-value {
  margin-left: 12rpx;
  font-size: 32rpx;
  color: #ffb300;
  font-weight: 700;
  letter-spacing: 2rpx;
  text-shadow: 0 2rpx 8rpx #ffd70022;
}
.review-textarea {
  flex: 1;
  min-height: 120rpx;
  border: 1px solid #eee;
  border-radius: 10rpx;
  padding: 12rpx;
  font-size: 28rpx;
  background: #fafbfc;
}
.image-list {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 12rpx;
}
.review-image-item {
  position: relative;
  width: 100rpx;
  height: 100rpx;
  margin-right: 12rpx;
  margin-bottom: 12rpx;
  display: inline-block;
}
.review-image {
  width: 100%;
  height: 100%;
  border-radius: 10rpx;
  object-fit: cover;
  box-shadow: 0 2rpx 8rpx #0001;
}
.delete-btn {
  position: absolute;
  top: -18rpx;
  right: -18rpx;
  width: 44rpx;
  height: 44rpx;
  line-height: 44rpx;
  text-align: center;
  background: linear-gradient(135deg, #ffb300, #ff6b6b);
  color: #fff;
  border-radius: 50%;
  font-size: 32rpx;
  font-weight: bold;
  z-index: 2;
  cursor: pointer;
  box-shadow: 0 4rpx 16rpx #ffb30033, 0 2rpx 8rpx #ff6b6b22;
  border: 2rpx solid #fff;
  transition: transform 0.15s, box-shadow 0.15s;
}
.delete-btn:active {
  transform: scale(0.92);
  box-shadow: 0 2rpx 8rpx #ffb30022;
}
.upload-btn {
  width: 100rpx;
  height: 100rpx;
  background-color: #f5f5f5;
  border-radius: 10rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12rpx;
  margin-bottom: 12rpx;
  border: 1px dashed #bbb;
  cursor: pointer;
}
.upload-icon {
  font-size: 48rpx;
  color: #bbb;
}
.submit-btn {
  width: 100%;
  background: linear-gradient(135deg, #ffb300, #ff6b6b);
  color: #fff;
  font-size: 32rpx;
  border-radius: 32rpx;
  border: none;
  margin-top: 24rpx;
  font-weight: 700;
  box-shadow: 0 8rpx 32rpx #ffb30022;
  transition: background 0.2s;
  letter-spacing: 2rpx;
}
.submit-btn:active {
  background: linear-gradient(135deg, #ffb300, #ffb300);
}
.success-tip {
  margin-top: 80rpx;
  text-align: center;
  color: #07c160;
  font-size: 32rpx;
  font-weight: 600;
}
.reviewed-tip {
  margin-top: 80rpx;
  text-align: center;
  color: #07c160;
  font-size: 32rpx;
  font-weight: 600;
}
.reviewed-content {
  margin-top: 20rpx;
  text-align: center;
}
.review-status-bar {
  width: 92vw;
  margin: 0 auto 18rpx auto;
  padding: 18rpx 0 8rpx 0;
  text-align: center;
  color: #ffb300;
  font-size: 28rpx;
  font-weight: 600;
  letter-spacing: 2rpx;
}
</style> 